define([
  'require',
  'jquery',
  'views/View',
  'views/Modal'
], function(require, $, View, Modal) {
  var Form = View.extend({

    events: {
      "submit form":			"stopSubmit"
    },
    
    render: function() {
      View.prototype.render.call(this);
      if(this.renderContain) {
	this.renderContain();
      }	
      return this;
    },
    
    getObjectFromForm: function(form) {
      var object = {};
      var self = this;

      // Function used to get an object from the differents fields of a form.
      var recursive =   function(fields, value, object) {
        object = object || {};
        if(fields.length == 1) { // Its a final property
          if(value) {
            object[fields[0]] = value;
          }
        } else { // Its an object
          if(!object[fields[0]]) { // Check if it contains the object
            object[fields[0]] = {};
          } 
          object[fields[0]] = recursive(fields.slice(1, fields.length), value, object[fields[0]]);
        }
        return object;
      };

      $(form).find(":input").each(function(i){
	//console.log("Procesando campo: " + this.name);
	var j;
	var fields = this.name.split(".");
	object = recursive(fields, this.value, object); // TODO change this function. Some improvements can be done.
	
      });
      //console.log(object);
      //console.log("Terminamos");
      return object;
    },

    stopSubmit: function(e) {
      // Clear all errors class
      e.preventDefault(); 
    },

    successHandler: function(model, response, updated) {
      console.log("ModalForm -> successHandler");
      
      //      console.log(!!this.collection.get(model.id));
      if(this.collection && !this.collection.getByCid(model.cid)) {
        console.log(model.url);
        model.fetch();
        this.collection.add(model);
      }
      this.close();
      this.showSuccessMessage(updated);
/*      var successModal = new Modal({template: successTemplate});
      successModal.render();*/
/*      var successMessage = new batzen.AlertMessage({title: "El subscriptor se ha guardado correctamente."});
      state.addAlertMessage(successMessage);*/
      
    },

    showSuccessMessage: function(updated) {},

    showFailureMessage: function() {},
    
    errorHandler: function(model, response) { // TODO improve this!
      console.log("ErrorHandler");
      console.log(response);
      // Clean old errors
      $(".error").removeClass("error");
      // Clean old help errors
      $(".help-inline").html("");
      var rJson = jQuery.parseJSON(response.responseText);
      //console.log(rJson);
      var errors = this.$(".errors").empty();
      for(var key in rJson) {
        var $inputField =  $("input[name='"+ key+"']");
        var error = rJson[key];
        console.log(error);
        if($inputField) {
	  $inputField.parent().parent().addClass("error");
	  $(".help-inline", $inputField.parent()).html(error);
        } else {
          errors.append(error);
        }
      }

      this.showFailureMessage();
      model.set(model.previousAttributes()); // TODO remove this line.
      model.clear({silent: true}); // TODO check if this is correct.
    }

  });

  return Form;
});